package com.imooc.imoocbilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.imoocbilibili.utils.FastDFSUtil;
import com.imooc.imoocbilibili.utils.MD5Util;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.imooc.imoocbilibili.mapper.FileMapper;
import com.imooc.imoocbilibili.entity.File;
import com.imooc.imoocbilibili.service.FileService;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Service("fileService")
@RequiredArgsConstructor
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    private final FileMapper fileMapper;
    private final FastDFSUtil fastDFSUtil;

    @Override
    public Page<File> queryPage(Integer pageNo, Integer pageSize) {
        Page<File> page = this.page(
                new Page<>(pageNo, pageSize),
                // 拼接查询条件
                new LambdaQueryWrapper<File>()
        );

        return page;
    }

    public String uploadFileBySlices(MultipartFile slice,
                                     String fileMD5,
                                     Integer sliceNo,
                                     Integer totalSliceNo) throws Exception {
//        File dbFileMD5 = fileMapper.selectOne(new LambdaQueryWrapper<File>()
//                .eq(File::getMd5, fileMD5));
//        if (dbFileMD5 != null) {
//            return dbFileMD5.getUrl();
//        }
        String url = fastDFSUtil.uploadFileBySlices(slice, fileMD5, sliceNo, totalSliceNo);
//        if (!StringUtil.isNullOrEmpty(url)) {
//            dbFileMD5 = new File();
//            dbFileMD5.setCreatetime(new Date());
//            dbFileMD5.setMd5(fileMD5);
//            dbFileMD5.setUrl(url);
//            dbFileMD5.setType(fastDFSUtil.getFileType(slice));
//            fileMapper.insert(dbFileMD5);
//        }
        return url;
    }

    public String getFileMD5(MultipartFile file) throws Exception {
        return MD5Util.getFileMD5(file);
    }

    @Override
    public void slices(MultipartFile file) throws Exception {
        fastDFSUtil.convertFileToSlices(file);
    }

}